package compound.repository

import java.awt.Color
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import org.apache.log4j.Logger
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware

/**
 * accesses an image for
 */

class ImageService implements ApplicationContextAware {

  //needed for url generation
  def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib()
  
  File imageDir = null
  /**
   * reference to the render service
   */
  RenderService renderService

  //injected application context
  ApplicationContext applicationContext 

  boolean transactional = true

  public static int THUMNAIL_SIZE = 110
  public static int SMALL_SIZE = 160

  public static int MEDIUM_SIZE = 240
  public static int LARGE_SIZE = 480

  /**
   *
   * calculates an image of the specified size for us
   * @param compund
   * @param size
   * @return path to the file location
   */
  String getStructure(def fileName, String inchi, int size=320, Color color = Color.WHITE) {

    if(fileName == null){
      throw new NullPointerException("please make sure that you specify a filename != null")
    }

    if(inchi == null){
      throw new NullPointerException("please make sure that the inchi is != null")
    }
    imageDir = applicationContext.getResource("images/").getFile()
    String mainDir = "/" + imageDir.getName()
    imageDir = new File(imageDir, "compounds")
    mainDir = mainDir + "/" + imageDir.getName()
    if (!imageDir.exists()) {
      imageDir.mkdirs()
    }
    String name = "${fileName}-${size}-${color}.png"
    String finalName = g.createLinkTo(dir: mainDir, file: name)

    File image = new File(imageDir, name);

    if (!image.exists()) {
      log.debug "we need to generate a new image for ${inchi}"
      BufferedImage img = renderService.renderToImage(inchi, size, size, color)

      ImageIO.write(img, "PNG", image)
    }

    return finalName
  }

  /**
   * calculates a thumbnail for us
   * @param compound
   * @return string to the file location
   */
  String getThumbmail(def name, String inchi, Color color = Color.WHITE) {
    return getStructure(name, inchi, THUMNAIL_SIZE, color)
  }

  /**
   * calcualtes a small image for us
   * @param compound
   * @return string to the file location
   *
   */
  String getSmall(def name, String inchi, Color color = Color.WHITE) {
    return getStructure(name, inchi, SMALL_SIZE, color)

  }

  /**
   * calculates a medium image for us
   * @param compound
   * @return string to the file location
   */
  String getMedium(def name, String inchi, Color color = Color.WHITE) {
    return getStructure(name, inchi, MEDIUM_SIZE, color)

  }

  /**
   * calculates a large image for us
   * @param compound
   * @return string for the file location
   *
   */
  String getLarge(def name, String inchi, Color color = Color.WHITE) {
    return getStructure(name, inchi, LARGE_SIZE, color)
  }


}